package com.reservation.mapper;

import com.reservation.entity.Product;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 商品数据访问接口
 */
@Mapper
@Repository
public interface ProductMapper {

    /**
     * 插入新商品
     */
    @Insert("INSERT INTO products(name, price, image, stock, description, is_active, created_at, updated_at) " +
           "VALUES(#{name}, #{price}, #{image}, #{stock}, #{description}, #{isActive}, NOW(), NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Product product);

    /**
     * 更新商品
     */
    @Update("UPDATE products SET name=#{name}, price=#{price}, image=#{image}, " +
           "stock=#{stock}, description=#{description}, is_active=#{isActive}, updated_at=NOW() " +
           "WHERE id=#{id}")
    int update(Product product);

    /**
     * 根据ID查询商品
     */
    @Select("SELECT * FROM products WHERE id=#{id}")
    Product selectById(Long id);

    /**
     * 根据ID查找激活的商品
     */
    @Select("SELECT * FROM products WHERE id=#{id} AND is_active=true")
    Product selectByIdAndActive(Long id);

    /**
     * 查找所有激活的商品
     */
    @Select("SELECT * FROM products WHERE is_active=true ORDER BY id ASC")
    List<Product> selectAllActive();

    /**
     * 查找有库存的商品
     */
    @Select("SELECT * FROM products WHERE is_active=true AND stock > 0 ORDER BY id ASC")
    List<Product> selectAvailable();

    /**
     * 根据名称模糊查询商品
     */
    @Select("SELECT * FROM products WHERE is_active=true AND LOWER(name) LIKE CONCAT('%', LOWER(#{name}), '%') ORDER BY id ASC")
    List<Product> selectByNameLike(String name);

    /**
     * 查找库存不足的商品
     */
    @Select("SELECT * FROM products WHERE is_active=true AND stock <= #{threshold} ORDER BY stock ASC")
    List<Product> selectLowStock(Integer threshold);

    /**
     * 删除商品
     */
    @Delete("DELETE FROM products WHERE id=#{id}")
    int deleteById(Long id);

    /**
     * 批量删除商品
     */
    @Delete("<script>" +
            "DELETE FROM products WHERE id IN " +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int deleteByIds(@Param("ids") List<Long> ids);
}